/*
 * DA4.c
 *
 * Created: 3/23/2014 1:43:26 PM
 *  Author: Omar Salazar
 */ 
#include <avr/io.h>
#define F_CPU 1000000UL	//1MHz
#include <util/delay.h>

void change_duty_cycle(int pwm)		// this function is meant to always change the prescaler of timer0 and timer2
{
	if(pwm == 0)
	{
		TCCR0B = 0x01;	//no prescaler
		TCCR2B = 0x01;	//no prescaler
	}
	if(pwm == 1)
	{
		TCCR0B = 0x02;	//prescaler 8
		TCCR2B = 0x02;	//prescaler 8
	}
	if(pwm == 2)
	{
		TCCR0B = 0x03;	//prescaler 64
		TCCR2B = 0x03;	//prescaler 64
	}
	if(pwm == 3)
	{
		TCCR0B = 0x04;	//prescaler 256
		TCCR2B = 0x04;	//prescaler 256
	}
}
int main()
{
	//set timer 0 to fast PWM mode with OCR changing from 10% to 90% of its max value.
	TCCR0A = 0xA3;	//Set OC0A and OC0B to clear on compare match and set at bottom. Fast PWM tops at 0xFF and updates
	TCCR0B = 0x01;	//OCR1A at the bottom. WGM01:1, WGM00:1, WGM02:0, CS00:1 (no prescaler)
	TCCR2A = 0x83;	//Set OC2A to clear on compare match and set at bottom. Fast PWM tops at 0xFF and updates OCR2A
	TCCR2B = 0x01;	//at the bottom.  WGM21:1, WGM20:1, WGM22:0, CS20:1 (no prescaler)
	DDRD = ((1<<PORTD6)|(1<<PORTD5));		// set ports D6 and D5 to output
	DDRB = (1<<PORTB3);						// set port B3 to output
	while(1)
	{
		int pwm = 0;		//pwm starts off with no prescaler, this keeps tracks of the adjustments
		//slowly increase the duty cycle of the red
		for (int i=26; i<230; i++)		//from 10% to 90%
		{
			OCR0B = i;
			_delay_ms(4);
		}
		//slowly decrease the duty cycle of the red
		for (int i=230; i>26; i--)		//from 90% to 10%
		{
			OCR0B = i;
			_delay_ms(4);
		}
		//slowly increase the duty cycle of the green
		for (int i=26; i<230; i++)		//from 10% to 90%
		{
			OCR0A = i;
			_delay_ms(4);
		}
		//slowly decrease the duty cycle of the green
		for (int i=230; i>26; i--)		//from 90% to 10%
		{
			OCR0A = i;
			_delay_ms(4);
		}
		//slowly increase the duty cycle of the blue
		for (int i=26; i<230; i++)		//from 10% to 90%
		{
			OCR2A = i;
			_delay_ms(4);
		}
		//slowly decrease the duty cycle of the blue
		for (int i=230; i>26; i--)		//from 90% to 10%
		{
			OCR2A = i;
			_delay_ms(4);
		}
		change_duty_cycle(pwm);			//change timer0 and timer2 prescaler
		pwm++;							//increment pwm
		if(pwm == 3)					//if pwm is 3, reset it back to 0
		pwm = 0;

	}
	return 0;
}